
import axios from 'axios'

const request = axios.create({
    timeout:5000
})

request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

    const token = localStorage.getItem('token')
    if (token) {
        // 在请求头中添加token，根据后端要求设置合适的header名称
        // config.headers['Authorization'] = `Bearer ${token}`
        // 或者根据后端要求使用其他格式，如:
        config.headers['token'] = token
    }
    return config
},error => {
    return Promise.reject(error)
    })

request.interceptors.response.use(response => {
    let res = response.data

    if (response.config.responseType === 'blob'){
        return res
    }
    if (typeof res === 'string'){
        res = res ? JSON.parse(res) : res
    }
    if (response.data.code === 401) { // 假设401表示未授权
        // 清除本地token
        localStorage.removeItem('token')
        // 跳转到登录页
        window.location.href = '/login'
    }
    if (response.data.code === 500) { // 假设401表示未授权
        // 清除本地token
        localStorage.removeItem('token')
        // 跳转到登录页
        window.location.href = '/login'
    }

    return res
},error => {
    if (error.response && error.response.status === 401) {
        // token过期或无效
        localStorage.removeItem('token')
        // 跳转到登录页
        window.location.href = '/login'
    }
    return Promise.reject(error)

})

export default request